package com.lagou.consumer;

import com.lagou.entity.COrder;
import com.lagou.repository.COrderRepository;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Optional;

/**
 * @author jinshanzhang
 * @version 1.0
 * @description
 * @date 2021/11/1 7:00 下午
 */
@Component
public class PayTimeoutConsumer {

    @Autowired
    private COrderRepository cOrderRepository;

    /**
     * 消费死信队列
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "queue.pay.waiting.dlx")
    public void getMyMessage(Message message, Channel channel) {
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println("订单超时未支付，自动取消订单.....");
            String orderId = new String(message.getBody());
            // 确认消息
            channel.basicAck(deliveryTag, false);
            COrder condition = new COrder();
            condition.setOrderId(orderId);
            Example<COrder> example = Example.of(condition);
            Optional<COrder> optional = cOrderRepository.findOne(example);
            if (ObjectUtils.isEmpty(optional)) {
                return;
            }
            COrder cOrder = optional.get();
            cOrder.setStatus("60");
            cOrderRepository.saveAndFlush(cOrder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
